package com.cscec.omega.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cscec.omega.utils.JsonSchemaUtil;
import com.cscec.omega.utils.ResponseEntity;
import com.cscec.omega.utils.SchemaUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传验证
 * 1、签名验证
 * 2、jsonSchema验证
 */

@Aspect
@Component
public class UploadAop {

    private static Logger logger = LoggerFactory.getLogger(UploadAop.class);

    @Pointcut("execution(public * com.cscec.omega.controller.UniversalController.*(..))")
    public void pointCut(){
        logger.info("切点进入....");
    }

    /**
     * 切点之前执行
     * @param joinPoint
     */
//    @Before("pointCut()")
    public void cutBefore(JoinPoint joinPoint) throws Throwable {
        logger.info("方法执行之前...");
    }

    /**
     * 切点之后执行
     * @param joinPoint
     */
//    @After("pointCut()")
    public void cutAfter(JoinPoint joinPoint){
        logger.info("方法执行之后...");
    }

    @Around("pointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, Object> paramMap = new HashMap<>();

        //得到参数列表
        Object[] args = joinPoint.getArgs();
        //得到参数名列表
        String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        for (int i=0; i< parameterNames.length; i++) {
            String paramName = parameterNames[i];
            Object paramValue = args[i];
            paramMap.put(paramName, paramValue);

            if (paramValue instanceof JSONObject){
                logger.info("type: JSONObject");
            }else if(paramValue instanceof String){
                logger.info("type: String");
            }
        }
        logger.info("paramMap: {}", paramMap);

        JSONObject jsonObject = JSONObject.parseObject(paramMap.get("jsonObject").toString());
        String sign = jsonObject.getString("sign");
        String appId = String.valueOf(paramMap.get("appId"));
        String moduleId = String.valueOf(paramMap.get("moduleId"));
//        if (!"6a220a09-3c9e-48ca-830d-c2ad1acf4c13".equals(sign)){
//            return new ResponseEntity(-1, "签名错误");
//        }
        String key = appId+"_"+moduleId+"_"+joinPoint.getSignature().getName();
        String jsonSchema = SchemaUtil.getSchema(key);
        boolean schema = JsonSchemaUtil.verify(jsonSchema, JSON.toJSONString(paramMap.get("jsonObject")));
        if (!schema){
            return new ResponseEntity(-1, "格式错误");
        }
        return joinPoint.proceed();
    }

        /**
         * 获取请求头
         */
    private Map<String, String> getHeaders(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        // 获取请求头
        Enumeration<String> enumeration = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headers.put(name, value);
        }
        logger.info("headers: {}", headers);
        return headers;
    }
}
